from flask import Flask, jsonify, request
import face_recognition
import nacos

# flask发布的 人脸识别的接口，可通过http 验证两张图片是否是同一个人；
app = Flask(__name__)

# 验证图片的后缀和文件大小
ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif'}
app.config['MAX_CONTENT_LENGTH'] = 1 * 1024 * 1024

# TODO 改为配置文件
SERVER_ADDRESSES = "106.12.112.30:8848"
NAMESPACE = "c45314bb-bf54-4a23-9bba-e27a5f6c909b"
# no auth mode
client = nacos.NacosClient(SERVER_ADDRESSES, namespace=NAMESPACE)
# auth mode
# client = nacos.NacosClient(SERVER_ADDRESSES, namespace=NAMESPACE, username="nacos", password="nacos")

# 获取配置文件
data_id = "zt-face-reco.yaml"
group = "RENREN_CLOUD_GROUP"
# print(client.get_config(data_id, group))

# 注册服务
service_name = 'zt-face-reco'
ip = '192.168.2.27'
cluster_name = 'zt-face-reco'

client.add_naming_instance(service_name, ip, 5001)


# 验证可上传的图片
def allowed_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS


@app.route('/', methods=['GET'])
def helloWord():
    return "Hello word!"


##TODO 加入 try catch机制

# 图片对比服务接口。
@app.route('/compare', methods=['POST'])
def compare_images():
    ##TODO 检查文件大小、和文件扩展名
    # 没有图片文件
    files = request.files
    if len(files) < 2:
        return "图片数量不正确，请传入两张图片进行对比", 400

    img1 = request.files['img1']
    img2 = request.files['img2']

    result = do_compare(img1, img2);
    return jsonify(result)


# face_recognition 人脸对比的python 核心库，参考在线文档：https://face-recognition.readthedocs.io/en/latest/readme.html
def do_compare(file1, file2):
    img = face_recognition.load_image_file(file1)
    file1_face_encodings = face_recognition.face_encodings(img)
    img2 = face_recognition.load_image_file(file2)
    file2_face_encodings = face_recognition.face_encodings(img2)
    if len(file1_face_encodings) > 0 and len(file2_face_encodings) > 0:
        # 进行比对，tolerance的精度参数查看官方文档
        match_results = face_recognition.compare_faces(file1_face_encodings, file2_face_encodings[0], tolerance=0.36)
        if match_results[0]:
            return True
        else:
            return False
    else:
        return False


# server服务器启动点
if __name__ == "__main__":
    app.run(host='0.0.0.0', port=5001, debug=True)
